package com.apes.scm.masterdata.frame.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.frame.model.Channel;
import com.apes.scm.masterdata.frame.repository.ChannelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 功能：渠道 Service
 *
 * @author HuJianlin
 * @create 2018-03-08 14:35
 */
@Service("channelService")
public class ChannelService extends DomainService {

    @Autowired
    ChannelRepository channelRepository;

    public Channel save(SimpleRequest request) {
        Channel channel = request.getO(Channel.class);
        channelRepository.saveAndFlush(channel);
        return channel;
    }

    public Channel update(SimpleRequest request){
        // 检查数据
        this.checkData(request);

        Channel channel = request.getO(Channel.class);
        return channelRepository.saveAndFlush(channel);
    }

    public void checkData(SimpleRequest request){
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        Channel oldChannel = channelRepository.findOne(id);
        if (oldChannel == null) throw new RuntimeException("招聘申请单【" + id + "】在系统中不存在。");
        if (oldChannel.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }

    public String delete(SimpleRequest request){
        this.checkData(request);
        channelRepository.delete(request.getO(Channel.class));
        return "删除成功";
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public List<Channel> findAll(SimpleRequest request) {
        List<Channel> channels = channelRepository.findAll();
        return channels;
    }

    /**
     * 查询所有类型有效ID
     * @param request
     * @return
     */
    public List<String> findIdAllByType(SimpleRequest request){
        return channelRepository.findIdAllByType();
    }

}
